﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Options.IBClient.Component;
using Options.IBClient.WinApp.Extensions;

using Krs.Ats.IBNet;
using Krs.Ats.IBNet.Contracts;
using System.Threading;
using System.Threading.Tasks;
using Options.IBClient.Component.Enums;


namespace Options.IBClient.WinApp
{
    delegate void SetTextCallback(string text);
    public partial class DeltaComputaion : Form
    {
        Krs.Ats.IBNet.IBClient client = new Krs.Ats.IBNet.IBClient();
        static System.Windows.Forms.Timer RefreshTimer = new System.Windows.Forms.Timer();

        delegate void SetDisplayMarketData(List<MarketData> md);
        delegate void SetDisplayOptionData(List<OptionTrigger> md);
        delegate void SetDisplayOptionCompute(List<OptionComputation> oc);
        delegate void SetDisplayOpenOrder(DataTable dt);
        delegate void SetDisplaySecuritySymbols(List<Security> s);
        delegate void SetDisplaySettings(List<Settings> settings);
        delegate void SetDisplayDataTable(DataTable dt);
        delegate void SetDisplayCommonSettings(List<CommonSettings> comset);
        delegate void SetDisplayLabel(string message);


        private string cmbsymbolSelectedValue = string.Empty;
        private string cmbrightTypeSelectedValue = string.Empty;
        private bool m_isExiting;
        //private bool refreshMarket = true;
        private static Contract contract;
        private List<Thread> _workers = new List<Thread>();
        private SplashScreen pbf;
        private Refresh refresh;
        delegate void SetDisplayProgressDelegate(int progress);
        private List<Security> securities = new List<Security>();
        private Object thisLock = new Object();

        public DeltaComputaion()
        {
            InitializeComponent();
            pbf = new SplashScreen();
            pbf.Show();
            pbf.Update();
            this.FormClosing += new FormClosingEventHandler(this.DeltaComputation_FormClosing);

            try
            {
                SqlHelper helper = new SqlHelper();
                if (helper.IsServerConnected())
                {
                    pbf.UpdateProgress(25);
                    lblSqlconnectivity.Text = "Connected";
                    lblSqlconnectivity.BackColor = System.Drawing.Color.GreenYellow;
                    helper.AddLog("SQL server connectivity ok");
                    securities = helper.GetSymbols();
                    pbf.UpdateProgress(30);


                    Parallel.ForEach(securities, security =>
                    {
                        ClientYahoo cYahoo = new ClientYahoo(security.Symbol);
                        String receivedData = cYahoo.getSMA();
                        string[] contents = receivedData.Split(',');
                        helper.AddSMA(contents[0].ToString().Replace("\"", " ").Trim(), contents[1].ToString().Trim(), contents[2].ToString().Trim(), contents[3].ToString().Trim());

                    }//close lambda expression
                         ); //close method invocation 
                    lblYahooClient.Text = "Connected";
                    lblYahooClient.BackColor = System.Drawing.Color.GreenYellow;

                    pbf.UpdateProgress(50);
                    client.CurrentTime += client_CurrentTime;
                    client.Error += client_Error;
                    client.TickPrice += client_TickPrice;
                    client.TickOptionComputation += client_TickOptionComputation;
                    client.OrderStatus += client_OrderStatus;
                    client.TickSnapshotEnd += client_TickSnapshotEnd;
                    client.ContractDetails += client_ContractDetails;


                    client.ThrowExceptions = true;
                    connectClient();

                    if (client.Connected)
                    {
                        FillSecuritySymbols();
                        FillSettings();
                        FillCommonSettings();
                        FillDeltaCompute();
                        //  FillOptionTriggers();
                        FillComboSymbols();
                        FillComboRightType();
                        FillOpenOrders();
                        FillWeeklyExpiry();
                        MarketDataSetGrid();


                        DataTable dt = (new SqlHelper()).getExpiryDates();
                        lstViewExpiry.GridLines = true;
                        lstViewExpiry.Columns.Add("Expiry Date", -2, HorizontalAlignment.Right);
                        foreach (DataRow row in dt.Rows)
                        {
                            ListViewItem newItem = lstViewExpiry.Items.Add(DateTime.Parse(row["Expiry Date"].ToString()).ToShortDateString());
                            newItem.Checked = (bool)row["Checked"];
                        }

                        pbf.UpdateProgress(60);

                        requestDeltaData();

                        pbf.UpdateProgress(90);

                        RefreshTimer.Tick += new EventHandler(RefreshTimerEventProcessor);
                        RefreshTimer.Interval = 60000;
                        RefreshTimer.Start();
                    }
                }
            }
            catch (Exception ex)
            {
                this.SetTWSErrorMsg("Error: " + ex.Message.ToString());
                Log.LogMessage(ex.Message.ToString());
            }

            pbf.Close();
        }

        private void DeltaComputaion_Load(object sender, EventArgs e)
        {
        }

        private void DeltaComputation_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!m_isExiting)
            {
                DialogResult frmclose = MessageBox.Show("Are you sure want to exit?", "Closing...", MessageBoxButtons.YesNo);
                if (frmclose == DialogResult.No)
                {
                    e.Cancel = true;
                }
                if (frmclose == DialogResult.Yes)
                {
                    if (RefreshTimer.Enabled)
                    {
                        RefreshTimer.Stop();
                    }
                    foreach (Thread t in _workers)
                    {
                        if (t.IsAlive)
                            t.Abort();
                    }
                    m_isExiting = true;
                    Application.Exit();
                }
            }
        }

        #region Bind
        private void FillSecuritySymbols()
        {


            DataGridViewTextBoxColumn symbolColumn = new DataGridViewTextBoxColumn();
            symbolColumn.Name = "Symbol";
            symbolColumn.DataPropertyName = "Symbol";
            symbolColumn.ReadOnly = true;
            symbolColumn.SortMode = DataGridViewColumnSortMode.Automatic;
            gvSecurityOption.Columns.Add(symbolColumn);


            DataGridViewCheckBoxColumn IsWeeklyColumn = new DataGridViewCheckBoxColumn();
            IsWeeklyColumn.Name = "IsWeekly";
            IsWeeklyColumn.DataPropertyName = "IsWeekly";
            IsWeeklyColumn.HeaderText = "Weekly Option";
            gvSecurityOption.Columns.Add(IsWeeklyColumn);

            DataGridViewImageColumn deleteButton = new DataGridViewImageColumn();
            deleteButton.Name = "Delete";
            deleteButton.ToolTipText = "Delete";
            deleteButton.Image = Image.FromFile("trash.ico");
            deleteButton.ImageLayout = DataGridViewImageCellLayout.Normal;
            gvSecurityOption.Columns.Add(deleteButton);

            this.gvSecurityOption.AutoGenerateColumns = false;
            securities.Sort();
            DisplaySecuritySymbols(securities);
        }

        private void FillSettings()
        {
            SqlHelper helper = new SqlHelper();

            DataGridViewButtonColumn updateButton = new DataGridViewButtonColumn();
            updateButton.Name = "Update";
            updateButton.Text = "Update";
            updateButton.UseColumnTextForButtonValue = true;
            gvSettings.Columns.Add(updateButton);

            DataGridViewTextBoxColumn nameColumn = new DataGridViewTextBoxColumn();
            nameColumn.HeaderText = "Setting Name";
            nameColumn.Name = "Name";
            nameColumn.DataPropertyName = "Name";
            nameColumn.ReadOnly = true;
            gvSettings.Columns.Add(nameColumn);

            DataGridViewTextBoxColumn minColumn = new DataGridViewTextBoxColumn();
            minColumn.HeaderText = "Minimum";
            minColumn.Name = "Min";
            minColumn.DataPropertyName = "Min";
            gvSettings.Columns.Add(minColumn);

            DataGridViewTextBoxColumn maxColumn = new DataGridViewTextBoxColumn();
            maxColumn.HeaderText = "Maximum";
            maxColumn.Name = "Max";
            maxColumn.DataPropertyName = "Max";

            gvSettings.Columns.Add(maxColumn);

            DataGridViewTextBoxColumn typeColumn = new DataGridViewTextBoxColumn();
            typeColumn.HeaderText = "Setting Type";
            typeColumn.Name = "Type";
            typeColumn.DataPropertyName = "Type";
            typeColumn.ReadOnly = true;
            gvSettings.Columns.Add(typeColumn);

            this.gvSettings.AutoGenerateColumns = false;
            DisplaySettings(helper.GetSettings());
        }

        private void FillCommonSettings()
        {
            SqlHelper helper = new SqlHelper();

            DataGridViewButtonColumn updateButton = new DataGridViewButtonColumn();
            updateButton.Name = "Update";
            updateButton.Text = "Update";
            updateButton.UseColumnTextForButtonValue = true;
            gvCommon.Columns.Add(updateButton);

            DataGridViewTextBoxColumn nameColumn = new DataGridViewTextBoxColumn();
            nameColumn.HeaderText = "Setting Name";
            nameColumn.Name = "Name";
            nameColumn.DataPropertyName = "Name";
            nameColumn.ReadOnly = true;
            gvCommon.Columns.Add(nameColumn);

            DataGridViewTextBoxColumn minColumn = new DataGridViewTextBoxColumn();
            minColumn.HeaderText = "Value";
            minColumn.Name = "Value";
            minColumn.DataPropertyName = "Value";
            gvCommon.Columns.Add(minColumn);

            this.gvCommon.AutoGenerateColumns = false;
            DisplayCommonSettings(helper.GetCommonSettings());
        }

        private void FillComboSymbols()
        {
            SqlHelper helper = new SqlHelper();
            cmbSymbol.DataSource = securities;
            cmbSymbol.DisplayMember = "Symbol";
            cmbSymbol.ValueMember = "SecurityId";
        }

        private void FillComboRightType()
        {
            // Create a new DataTable.
            System.Data.DataTable table = new DataTable("ParentTable");
            // Declare variables for DataColumn and DataRow objects.
            DataColumn column;
            DataRow row;

            // Create new DataColumn, set DataType,  // ColumnName and add to DataTable.    
            column = new DataColumn();
            column.DataType = System.Type.GetType("System.Int32");
            column.ColumnName = "id";
            column.ReadOnly = true;
            column.Unique = true;
            // Add the Column to the DataColumnCollection.
            table.Columns.Add(column);

            // Create second column.
            column = new DataColumn();
            column.DataType = System.Type.GetType("System.String");
            column.ColumnName = "RightType";

            // Add the column to the table.
            table.Columns.Add(column);

            row = table.NewRow();
            row["id"] = 0;
            row["RightType"] = "Put";
            table.Rows.Add(row);
            table.AcceptChanges();

            row = table.NewRow();
            row["id"] = 1;
            row["RightType"] = "Call";
            table.Rows.Add(row);
            table.AcceptChanges();

            comboBox1.DataSource = table;
            comboBox1.DisplayMember = "RightType";
            comboBox1.ValueMember = "id";

        }

        private void FillOpenOrders()
        {
            //DataGridViewButtonColumn buyButton = new DataGridViewButtonColumn();
            ////buyButton.HeaderText = "Buy";
            //buyButton.Name = "Buy";
            //buyButton.Text = "Buy";
            //buyButton.UseColumnTextForButtonValue = true;
            //gvOpenOrders.Columns.Add(buyButton);

            //DataGridViewTextBoxColumn symColumn = new DataGridViewTextBoxColumn();
            //symColumn.HeaderText = "Symbol";
            //symColumn.Name = "Symbol";
            //symColumn.DataPropertyName = "Symbol";
            //symColumn.ReadOnly = true;
            //gvOpenOrders.Columns.Add(symColumn);

            //DataGridViewTextBoxColumn sizeColumn = new DataGridViewTextBoxColumn();
            //sizeColumn.HeaderText = "Quantity";
            //sizeColumn.Name = "Quantity";
            //sizeColumn.DataPropertyName = "Quantity";
            //sizeColumn.ReadOnly = true;
            //gvOpenOrders.Columns.Add(sizeColumn);

            //DataGridViewTextBoxColumn expColumn = new DataGridViewTextBoxColumn();
            //expColumn.HeaderText = "Days To Expire";
            //expColumn.Name = "Days To Expire";
            //expColumn.DataPropertyName = "Days To Expire";
            //expColumn.ReadOnly = true;
            //gvOpenOrders.Columns.Add(expColumn);

            //DataGridViewTextBoxColumn tpColumn = new DataGridViewTextBoxColumn();
            //tpColumn.HeaderText = "Trade Price";
            //tpColumn.Name = "Trade Price";
            //tpColumn.DataPropertyName = "Trade Price";
            //tpColumn.ReadOnly = true;
            //gvOpenOrders.Columns.Add(tpColumn);

            //DataGridViewTextBoxColumn mColumn = new DataGridViewTextBoxColumn();
            //mColumn.HeaderText = "Market Price";
            //mColumn.Name = "Market Price";
            //mColumn.DataPropertyName = "Market Price";
            //mColumn.ReadOnly = true;
            //gvOpenOrders.Columns.Add(mColumn);

            //DataGridViewTextBoxColumn wlColumn = new DataGridViewTextBoxColumn();
            //wlColumn.HeaderText = "% Win/Loss";
            //wlColumn.Name = "% Win/Loss";
            //wlColumn.DataPropertyName = "% Win/Loss";
            //wlColumn.ReadOnly = true;
            //gvOpenOrders.Columns.Add(wlColumn);

            //DataGridViewTextBoxColumn commColumn = new DataGridViewTextBoxColumn();
            //commColumn.HeaderText = "Actual Commission";
            //commColumn.Name = "Actual Commission";
            //commColumn.DataPropertyName = "Actual Commission";
            //commColumn.ReadOnly = true;
            //gvOpenOrders.Columns.Add(commColumn);

            //DataGridViewTextBoxColumn openOrdColumn = new DataGridViewTextBoxColumn();
            //openOrdColumn.HeaderText = "OpenOrderId";
            //openOrdColumn.Name = "OpenOrderId";
            //openOrdColumn.DataPropertyName = "OpenOrderId";
            //openOrdColumn.ReadOnly = true;
            //openOrdColumn.Visible = false;
            //gvOpenOrders.Columns.Add(openOrdColumn);


            //DataGridViewTextBoxColumn expdtColumn = new DataGridViewTextBoxColumn();
            //expdtColumn.HeaderText = "Expiry";
            //expdtColumn.Name = "Expiry";
            //expdtColumn.DataPropertyName = "Expiry";
            //expdtColumn.ReadOnly = true;
            //expdtColumn.Visible = false;
            //gvOpenOrders.Columns.Add(expdtColumn);

            //DataGridViewTextBoxColumn strikeColumn = new DataGridViewTextBoxColumn();
            //strikeColumn.HeaderText = "StrikePrice";
            //strikeColumn.Name = "StrikePrice";
            //strikeColumn.DataPropertyName = "StrikePrice";
            //strikeColumn.ReadOnly = true;
            //strikeColumn.Visible = false;
            //gvOpenOrders.Columns.Add(strikeColumn);

            //DataGridViewTextBoxColumn rightTypeColumn = new DataGridViewTextBoxColumn();
            //rightTypeColumn.HeaderText = "RightType";
            //rightTypeColumn.Name = "RightType";
            //rightTypeColumn.DataPropertyName = "RightType";
            //rightTypeColumn.ReadOnly = true;
            //rightTypeColumn.Visible = false;
            //gvOpenOrders.Columns.Add(rightTypeColumn);

            //DataGridViewTextBoxColumn bidColumn = new DataGridViewTextBoxColumn();
            //bidColumn.HeaderText = "BidPrice";
            //bidColumn.Name = "BidPrice";
            //bidColumn.DataPropertyName = "BidPrice";
            //bidColumn.ReadOnly = true;
            //bidColumn.Visible = false;
            //gvOpenOrders.Columns.Add(bidColumn);


            //this.gvOpenOrders.AutoGenerateColumns = false;
        }


        private void FillWeeklyExpiry()
        {
            SqlHelper helper = new SqlHelper();

            DataGridViewButtonColumn updateButton = new DataGridViewButtonColumn();
            updateButton.Name = "Update";
            updateButton.Text = "Update";
            updateButton.UseColumnTextForButtonValue = true;
            gvWeeklyDates.Columns.Add(updateButton);

            DataGridViewTextBoxColumn expiryColumn = new DataGridViewTextBoxColumn();
            expiryColumn.HeaderText = "Expiry Date";
            expiryColumn.Name = "Expiry Date";
            expiryColumn.DataPropertyName = "Expiry Date";
            expiryColumn.ReadOnly = true;
            gvWeeklyDates.Columns.Add(expiryColumn);

            DataGridViewTextBoxColumn dateColumn = new DataGridViewTextBoxColumn();
            dateColumn.HeaderText = "Run Date";
            dateColumn.Name = "Date";
            dateColumn.DataPropertyName = "Date";
            gvWeeklyDates.Columns.Add(dateColumn);

            this.gvWeeklyDates.AutoGenerateColumns = false;
            DisplayDataTable(helper.getCompleteWeeklyExpiryDates());
        }

        private void FillDeltaCompute()
        {
            DataGridViewTextBoxColumn expColumn = new DataGridViewTextBoxColumn();
            expColumn.HeaderText = "Expiry";
            expColumn.Name = "Expiry";
            expColumn.DataPropertyName = "Expiry";
            expColumn.ReadOnly = true;
            gvdeltaCompute.Columns.Add(expColumn);

            DataGridViewTextBoxColumn strikeColumn = new DataGridViewTextBoxColumn();
            strikeColumn.HeaderText = "StrikePrice";
            strikeColumn.Name = "StrikePrice";
            strikeColumn.DataPropertyName = "StrikePrice";
            strikeColumn.ReadOnly = true;
            gvdeltaCompute.Columns.Add(strikeColumn);

            DataGridViewTextBoxColumn bidColumn = new DataGridViewTextBoxColumn();
            bidColumn.HeaderText = "BidPrice";
            bidColumn.Name = "BidPrice";
            bidColumn.DataPropertyName = "BidPrice";
            bidColumn.ReadOnly = true;
            gvdeltaCompute.Columns.Add(bidColumn);

            DataGridViewTextBoxColumn askColumn = new DataGridViewTextBoxColumn();
            askColumn.HeaderText = "AskPrice";
            askColumn.Name = "AskPrice";
            askColumn.DataPropertyName = "AskPrice";
            askColumn.ReadOnly = true;
            gvdeltaCompute.Columns.Add(askColumn);

            DataGridViewTextBoxColumn deltaColumn = new DataGridViewTextBoxColumn();
            deltaColumn.HeaderText = "Delta";
            deltaColumn.Name = "Delta";
            deltaColumn.DataPropertyName = "Delta";
            deltaColumn.ReadOnly = true;
            gvdeltaCompute.Columns.Add(deltaColumn);

            DataGridViewTextBoxColumn gammaColumn = new DataGridViewTextBoxColumn();
            gammaColumn.HeaderText = "Gamma";
            gammaColumn.Name = "Gamma";
            gammaColumn.DataPropertyName = "Gamma";
            gammaColumn.ReadOnly = true;
            gammaColumn.DefaultCellStyle.BackColor = System.Drawing.Color.GreenYellow;
            gvdeltaCompute.Columns.Add(gammaColumn);

            DataGridViewTextBoxColumn vegaColumn = new DataGridViewTextBoxColumn();
            vegaColumn.HeaderText = "Vega";
            vegaColumn.Name = "Vega";
            vegaColumn.DataPropertyName = "Vega";
            vegaColumn.ReadOnly = true;
            vegaColumn.DefaultCellStyle.BackColor = System.Drawing.Color.GreenYellow;
            gvdeltaCompute.Columns.Add(vegaColumn);

            DataGridViewTextBoxColumn thetaColumn = new DataGridViewTextBoxColumn();
            thetaColumn.HeaderText = "Theta";
            thetaColumn.Name = "Theta";
            thetaColumn.DataPropertyName = "Theta";
            thetaColumn.ReadOnly = true;
            thetaColumn.DefaultCellStyle.BackColor = System.Drawing.Color.GreenYellow;
            gvdeltaCompute.Columns.Add(thetaColumn);

            this.gvdeltaCompute.AutoGenerateColumns = false;
        }

        private void MarketDataSetGrid()
        {
            DataGridViewTextBoxColumn symbolColumn = new DataGridViewTextBoxColumn();
            symbolColumn.HeaderText = "Symbol";
            symbolColumn.Name = "Symbol";
            symbolColumn.DataPropertyName = "Symbol";
            symbolColumn.ReadOnly = true;
            gvMarketData.Columns.Add(symbolColumn);

            DataGridViewTextBoxColumn dateAddedColumn = new DataGridViewTextBoxColumn();
            dateAddedColumn.HeaderText = "Refresh Time";
            dateAddedColumn.Name = "Refresh Time";
            dateAddedColumn.DataPropertyName = "DateAdded";
            dateAddedColumn.ReadOnly = true;
            gvMarketData.Columns.Add(dateAddedColumn);

            DataGridViewTextBoxColumn tickTypeColumn = new DataGridViewTextBoxColumn();
            tickTypeColumn.HeaderText = "Tick Type";
            tickTypeColumn.Name = "Tick Type";
            tickTypeColumn.DataPropertyName = "TickType";
            dateAddedColumn.ReadOnly = true;
            gvMarketData.Columns.Add(tickTypeColumn);

            DataGridViewTextBoxColumn tickPriceColumn = new DataGridViewTextBoxColumn();
            tickPriceColumn.HeaderText = "Tick Price";
            tickPriceColumn.Name = "Tick Price";
            tickPriceColumn.DataPropertyName = "TickPrice";
            tickPriceColumn.ReadOnly = true;
            gvMarketData.Columns.Add(tickPriceColumn);

            this.gvMarketData.AutoGenerateColumns = false;
        }

        private void DisplayMarketData(List<MarketData> mD)
        {
            if (this.gvMarketData.InvokeRequired)
            {
                SetDisplayMarketData d = new SetDisplayMarketData(DisplayMarketData);
                this.Invoke(d, new object[] { mD });
            }
            else
            {
                if (mD.Count > 0)
                {
                    this.gvMarketData.DataSource = mD;
                }
            }
        }

        private void DisplayOptionCompute(List<OptionComputation> oc)
        {
            if (this.gvdeltaCompute.InvokeRequired)
            {
                SetDisplayOptionCompute d = new SetDisplayOptionCompute(DisplayOptionCompute);
                this.Invoke(d, new object[] { oc });
            }
            else
            {
                if (oc.Count > 0)
                {
                    this.gvdeltaCompute.DataSource = oc;
                }
            }
        }

        private void DisplaySecuritySymbols(List<Security> sec)
        {

            if (this.gvSecurityOption.InvokeRequired)
            {
                SetDisplaySecuritySymbols d = new SetDisplaySecuritySymbols(DisplaySecuritySymbols);
                this.Invoke(d, new object[] { sec });
            }
            else
            {
                if (sec.Count > 0)
                {
                    this.gvSecurityOption.DataSource = sec;
                }
            }
        }

        private void DisplaySettings(List<Settings> settings)
        {
            if (this.gvSettings.InvokeRequired)
            {
                SetDisplaySettings d = new SetDisplaySettings(DisplaySettings);
                this.Invoke(d, new object[] { settings });
            }
            else
            {
                if (settings.Count > 0)
                {
                    this.gvSettings.DataSource = settings;
                }
            }
        }


        private void DisplayDataTable(DataTable dt)
        {
            if (this.gvWeeklyDates.InvokeRequired)
            {
                SetDisplayDataTable d = new SetDisplayDataTable(DisplayDataTable);
                this.Invoke(d, new object[] { dt });
            }
            else
            {
                if (dt.Rows.Count > 0)
                {
                    this.gvWeeklyDates.DataSource = dt;
                }
            }
        }

        private void DisplayCommonSettings(List<CommonSettings> comsettings)
        {

            if (this.gvCommon.InvokeRequired)
            {
                SetDisplayCommonSettings d = new SetDisplayCommonSettings(DisplayCommonSettings);
                this.Invoke(d, new object[] { comsettings });
            }
            else
            {
                if (comsettings.Count > 0)
                {
                    this.gvCommon.DataSource = comsettings;
                }
            }
        }

        private void SetTWSErrorMsg(string text)
        {
            if (this.txtTWSErrorMsg.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetTWSErrorMsg);
                if (IsHandleCreated)
                    this.Invoke(d, new object[] { text });
            }
            else
            {
                this.txtTWSErrorMsg.WriteLine(text);
            }
        }

        private void SetDeltaLabel(string text)
        {

            if (this.lblDeltaCurrent.InvokeRequired)
            {
                SetDisplayLabel d = new SetDisplayLabel(SetDeltaLabel);
                if (IsHandleCreated)
                    this.Invoke(d, new object[] { text });
            }
            else
            {
                this.lblDeltaCurrent.Text = text;
            }
        }
        #endregion Bind

        #region Button Events

        private void gvSecurityOption_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            string symbol = string.Empty;
            string definition = string.Empty;
            SqlHelper helper = new SqlHelper();
            if (gvSecurityOption.Columns[e.ColumnIndex] is DataGridViewImageColumn && e.RowIndex != -1)
            {
                Task.Factory.StartNew(() => ModifySecurityDefinition(gvSecurityOption.Columns[e.ColumnIndex].Name, (string)gvSecurityOption.Rows[e.RowIndex].Cells["Symbol"].Value, (bool)gvSecurityOption.Rows[e.RowIndex].Cells["ISWeekly"].Value));
            }

            if (gvSecurityOption.Columns[e.ColumnIndex] is DataGridViewCheckBoxColumn && e.RowIndex != -1)
            {
                Task.Factory.StartNew(() => ModifySecurityDefinition(gvSecurityOption.Columns[e.ColumnIndex].Name, (string)gvSecurityOption.Rows[e.RowIndex].Cells["Symbol"].Value, (bool)gvSecurityOption.Rows[e.RowIndex].Cells["ISWeekly"].Value));
            }
        }

        private void btnAddSecurityDefinition_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult dr = new DialogResult();
                AddSecurityDefinition cP = new AddSecurityDefinition();
                dr = cP.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    SqlHelper helper = new SqlHelper();
                    helper.AddSymbol(cP.txtSymbol.Text, cP.txtDefinition.Text);
                    DisplaySecuritySymbols(helper.GetSymbols());
                }
                else if (dr == DialogResult.Cancel)
                    cP.Close();
            }
            catch (Exception ex)
            {
                this.SetTWSErrorMsg("Error:" + ex.Message.ToString());
                Log.LogMessage(ex.Message.ToString());
            }
        }

        private void ModifySecurityDefinition(string Name, string Symbol, bool IsWeekly)
        {
            SqlHelper helper = new SqlHelper();
            if (Name == "Delete")
                helper.DeleteSymbol(Symbol.Trim());
            if (Name == "IsWeekly")
            {
                if (IsWeekly == false)
                    IsWeekly = true;
                else
                    IsWeekly = false;

                helper.UpdateIsWeeklySymbols(Symbol.Trim(), IsWeekly);
            }
            securities = helper.GetSymbols();
            securities.Sort();
            DisplaySecuritySymbols(securities);
        }
        
        private void gvSettings_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            Settings setting = new Settings();
            SqlHelper helper = new SqlHelper();
            if (gvSettings.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex != -1)
            {
                if (gvSettings.Columns[e.ColumnIndex].Name == "Update")
                {
                    setting.Name = (string)gvSettings.Rows[e.RowIndex].Cells["Name"].Value;
                    setting.Min = (decimal)gvSettings.Rows[e.RowIndex].Cells["Min"].Value;
                    setting.Max = (decimal)gvSettings.Rows[e.RowIndex].Cells["Max"].Value;
                    helper.UpdateSettings(setting);
                }
                DisplaySettings(helper.GetSettings());
            }
        }


        private void gvMarketData_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void lstViewExpiry_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            if (e.Item.Checked)
            {
                SqlHelper helper = new SqlHelper();
                helper.UpdateOptionExpiry(DateTime.Parse(e.Item.Text), true);
            }
            else
            {
                SqlHelper helper = new SqlHelper();
                helper.UpdateOptionExpiry(DateTime.Parse(e.Item.Text), false);
            }
        }

        private void gvCommon_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            CommonSettings setting = new CommonSettings();
            SqlHelper helper = new SqlHelper();
            if (gvCommon.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex != -1)
            {
                if (gvCommon.Columns[e.ColumnIndex].Name == "Update")
                {
                    setting.Name = (string)gvCommon.Rows[e.RowIndex].Cells["Name"].Value;
                    setting.Value = (string)gvCommon.Rows[e.RowIndex].Cells["Value"].Value;
                    helper.UpdateCommonSettings(setting);
                }
                DisplayCommonSettings(helper.GetCommonSettings());
            }
        }


        private void gvWeeklyDates_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            SqlHelper helper = new SqlHelper();
            if (gvWeeklyDates.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex != -1)
            {
                if (gvWeeklyDates.Columns[e.ColumnIndex].Name == "Update")
                {
                    DateTime dtDate = DateTime.Parse(gvWeeklyDates.Rows[e.RowIndex].Cells["Date"].Value.ToString());
                   DateTime dtExpiry = DateTime.Parse(gvWeeklyDates.Rows[e.RowIndex].Cells["Expiry Date"].Value.ToString());
                   helper.UpdateWeeklyOptionExpiry(dtExpiry, dtDate);
                }
                DisplayDataTable(helper.getCompleteWeeklyExpiryDates());
            }
        }

        private void lblSqlServerConnectivity_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string target = ((System.Windows.Forms.LinkLabel)(sender)).Text as string;
            if (null != target && target.Equals("Connected"))
            {
                MessageBox.Show("Sql server connected");
            }
            else
            {

            }

        }

        private void cmbSymbol_SelectedIndexChanged(object sender, EventArgs e)
        {

            // SqlHelper helper = new SqlHelper();
            cmbsymbolSelectedValue = ((Options.IBClient.Component.Security)(cmbSymbol.SelectedItem)).Symbol;
            string param = cmbsymbolSelectedValue + "," + cmbrightTypeSelectedValue;
            this.cmbSymbolbgWorker.RunWorkerAsync(param);
            cmbSymbol.Enabled = false;
            comboBox1.Enabled = false;
            //  this.gvdeltaCompute.DataSource = helper.GetLatestOptionDataBySymbolRightType(cmbsymbolSelectedValue, cmbrightTypeSelectedValue);

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            // SqlHelper helper = new SqlHelper();
            cmbrightTypeSelectedValue = ((System.Data.DataRowView)(comboBox1.SelectedItem)).Row.ItemArray[1].ToString();
            string param = cmbsymbolSelectedValue + "," + cmbrightTypeSelectedValue;
            this.cmbrightTypebgWorker.RunWorkerAsync(param);
            cmbSymbol.Enabled = false;
            comboBox1.Enabled = false;
            //  this.gvdeltaCompute.DataSource = helper.GetLatestOptionDataBySymbolRightType(cmbsymbolSelectedValue, cmbrightTypeSelectedValue);

        }
        #endregion

        #region Private Methods

        private void connectClient()
        {
            try
            {
                lock (thisLock)
                {
                    SqlHelper helper = new SqlHelper();
                    if (!client.Connected)
                    {
                        this.SetTWSErrorMsg("Connecting to IB....");
                        Log.LogMessage("Connecting to IB....");
                        client.Connect("127.0.0.1", int.Parse(helper.GetCommonSettingbyName("Port").Value), int.Parse(helper.GetCommonSettingbyName("ClientId").Value));
                    }
                    if (client.Connected)
                    {
                        //client.RequestCurrentTime();
                        lblStatus.Text = "IB Client Connected";
                        lblStatus.BackColor = Color.GreenYellow;
                        this.SetTWSErrorMsg("Client Connected");
                        Log.LogMessage("Client Connected");
                    }
                }
            }
            catch (Exception ex)
            {
                this.SetTWSErrorMsg("Error: " + ex.Message.ToString());
                Log.LogMessage(ex.Message.ToString());
            }
        }

        private void client_TickPrice(object sender, TickPriceEventArgs e)
        {
            try
            {
                SqlHelper helper = new SqlHelper();
                ResponseIBClient response = new ResponseIBClient();
                response.RequestId = e.TickerId;
                response.TickPrice = e.Price;
                response.TickType = e.TickType.ToString();
                helper.AddResponse(response);
            }
            catch (Exception ex)
            {
                this.SetTWSErrorMsg("Error: " + ex.Message.ToString());
                Log.LogMessage(ex.Message.ToString());
            }
        }

        private void client_TickSnapshotEnd(object sender, TickSnapshotEndEventArgs e)
        {
            try
            {
                SqlHelper helper = new SqlHelper();
                helper.UpdateRequestReceived(e.RequestId);
            }
            catch (Exception ex)
            {
                this.SetTWSErrorMsg("Error: " + ex.Message.ToString());
                Log.LogMessage(ex.Message.ToString());
            }
        }

        private void client_OrderStatus(object sender, OrderStatusEventArgs e)
        {
            try
            {
                SqlHelper helper = new SqlHelper();

                if (e.OrderId > 0)
                {
                    string sWhyHld = string.Empty;
                    if (string.IsNullOrEmpty(e.WhyHeld))
                    {
                        sWhyHld = string.Empty;
                    }
                    else
                    {
                        sWhyHld = e.WhyHeld;
                    }
                    helper.AddPlaceComboOrderRespose(e.OrderId, double.Parse(e.AverageFillPrice.ToString()), e.Status.ToString());
                    SetTWSErrorMsg("TWS Message, OrderID :" + e.OrderId.ToString() + " Status: " + e.Status.ToString() + " Average Fill Price: " + e.AverageFillPrice.ToString() + " Last Fill Price: " + e.LastFillPrice.ToString());
                    Log.LogMessage("OrderID :" + e.OrderId.ToString() + " Status: " + e.Status.ToString() + " Average Fill Price: " + e.AverageFillPrice.ToString() + " Last Fill Price: " + e.LastFillPrice.ToString());
                }

            }
            catch (Exception ex)
            {
                this.SetTWSErrorMsg("Error Message :" + ex.Message.ToString());
                Log.LogMessage(ex.Message.ToString());
            }
        }

        private void client_TickOptionComputation(object sender, TickOptionComputationEventArgs e)
        {
            try
            {

                if (e.TickType == TickType.ModelOption || e.TickType == TickType.LastOption)
                {
                    SqlHelper helper = new SqlHelper();
                    ResponseIBClient response = new ResponseIBClient();
                    response.RequestId = e.TickerId;
                    response.Delta = (double)e.Delta;
                    response.Theta = (double)e.Theta;
                    response.Gamma = (double)e.Gamma;
                    response.Vega = (double)e.Vega;
                    response.TickType = e.TickType.ToString();
                    helper.AddResponse(response);
                }
            }
            catch (Exception ex)
            {
                this.SetTWSErrorMsg("Error: " + ex.Message.ToString());
                Log.LogMessage(ex.Message.ToString());
            }
        }

        private void client_CurrentTime(object sender, CurrentTimeEventArgs e)
        {
            this.SetTWSErrorMsg("TWS: Connected at (UTC Time) " + e.Time.ToString());
            Log.LogMessage("TWS: Connected at (UTC Time) " + e.Time.ToString());
        }

        private void client_ContractDetails(object sender, ContractDetailsEventArgs e)
        {
            if (e.RequestId > 0 && e.ContractDetails.Summary.ContractId > 0)
            {
                SqlHelper helper = new SqlHelper();
                helper.UpdateConId(e.RequestId, e.ContractDetails.Summary.ContractId);
            }
        }

        private void client_Error(object sender, ErrorEventArgs e)
        {
            this.SetTWSErrorMsg(e.ErrorMsg);
            Log.LogMessage(e.ErrorMsg);
            if (e.TickerId > 0)
            {
                SqlHelper helper = new SqlHelper();
                string symbol = helper.GetSymbolbyRequest(e.TickerId);
                this.SetTWSErrorMsg(e.ErrorMsg + ", Symbol:" + symbol);
                Log.LogMessage(e.ErrorMsg + ", Symbol:" + helper.GetSymbolbyRequest(e.TickerId));
                if (helper.UpdateRequestIBClientError(e.TickerId))
                {
                }
                //client.CancelMarketData(e.TickerId);
            }
            else
            {
                this.SetTWSErrorMsg(e.ErrorMsg);
                Log.LogMessage(e.ErrorMsg);
            }
        }

        private void requestDeltaData()
        {
            if (!requestDeltabgWorker.IsBusy)
                this.requestDeltabgWorker.RunWorkerAsync();
        }

        #endregion

        #region Timer Events
        private void RefreshTimerEventProcessor(Object myObject, EventArgs myEventArgs)
        {
            try
            {
                //Make Inventory List
                SqlHelper helper = new SqlHelper();
                helper.makeInventoryList();
                helper.makeWeeklyInventoryList();

                if (!refreshbgWorker.IsBusy)
                {
                    gvMarketData.Enabled = false;
                    //gvOpenOrders.Enabled = false;
                    gvdeltaCompute.Enabled = false;
                    //gvOptionTrigger.Enabled = false;
                    refresh = new Refresh();
                    refresh.Location = new Point((this.Location.X + this.Width / 2) - (refresh.Width / 2),
                                                    (this.Location.Y + this.Height / 2) - (refresh.Height / 2));
                    refresh.StartPosition = FormStartPosition.Manual;
                    refresh.Show(this);
                    refresh.Update();
                    this.refreshbgWorker.RunWorkerAsync();
                    this.refreshbgWorker.WorkerReportsProgress = true;
                }



                if ((DateTime.Now.Minute) % 2 == 0)
                    requestDeltaData();
            }
            catch (Exception ex)
            {
                this.SetTWSErrorMsg("Error: " + ex.Message.ToString());
                Log.LogMessage(ex.Message.ToString());
            }
        }
        #endregion

        #region Back Ground Worker
        private void cmbSymbolbgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            SqlHelper helper = new SqlHelper();
            string param = (string)e.Argument;
            string[] arguments = param.Split(',');

            DisplayOptionCompute(helper.GetLatestOptionDataBySymbolRightType(arguments[0], arguments[1]));

        }

        private void cmbSymbolbgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {

        }

        private void cmbSymbolbgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            cmbSymbol.Enabled = true;
            comboBox1.Enabled = true;
        }


        private void cmbrightTypebgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            SqlHelper helper = new SqlHelper();
            string param = (string)e.Argument;
            string[] arguments = param.Split(',');

            DisplayOptionCompute(helper.GetLatestOptionDataBySymbolRightType(arguments[0], arguments[1]));
        }

        private void cmbrightTypebgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {

        }

        private void cmbrightTypebgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            cmbSymbol.Enabled = true;
            comboBox1.Enabled = true;
        }


        private void requestDeltabgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            //UpdateProgress(10);

            try
            {
                SqlHelper helper = new SqlHelper();

                RequestIBClient rIB = null;
                Contract contract = null;
                List<Security> marketSecurities = new List<Security>();
                marketSecurities = helper.GetSymbolslForMarketDataRequests();
                if (client.Connected)
                {
                    //Add Market Data Requests
                    foreach (Security security in marketSecurities)
                    {
                        string symbol = security.Symbol.Trim();
                        rIB = new RequestIBClient();
                        rIB.SecurityId = security.SecurityId;
                        rIB.SecurityType = Options.IBClient.Component.Enums.SecurityType.Stock;
                        rIB.RightType = Options.IBClient.Component.Enums.RightType.Undefined;
                        rIB.RequestId = helper.AddRequest(rIB).RequestId;
                    }


                    int QueueId = 1;
                    int rowcount = 0;
                    List<Security> optionSecurities = new List<Security>();
                    optionSecurities = helper.GetSymbolslForOptionUpdateRequests();
                    DataTable dt = new DataTable();
                    dt = helper.getExpiryDates();

                    DataTable dtWeeklyExpiry = new DataTable();
                    dtWeeklyExpiry = helper.getWeeklyExpiryDates();
                    //Add inventory request
                    List<RequestIBClient> inventoryLists = new List<RequestIBClient>();
                    inventoryLists = helper.GetSymbolslForInventoryRequests();
                    foreach (RequestIBClient inventoryList in inventoryLists)
                    {
                        inventoryList.RequestId = helper.AddRequest(inventoryList).RequestId;
                    }

                    //Add Option security request
                    foreach (Security security in optionSecurities)
                    {
                        MarketData marketData = helper.GetMarketDataBySymbol(security.Symbol.Trim());
                        for (int i = marketData.MinStrikePrice; i <= marketData.MaxStrikePrice; i++)
                        {
                            if (i > 0)
                            {
                                foreach (DataRow dr in dt.Rows)
                                {
                                    if (bool.Parse(dr["Checked"].ToString()))
                                    {
                                        string expiry = String.Format("{0:yyyyMMdd}", DateTime.Parse(dr["Expiry Date"].ToString()));

                                        //Add Option Put Data Requests
                                        rIB = new RequestIBClient();
                                        rIB.SecurityId = security.SecurityId;
                                        rIB.SecurityType = Options.IBClient.Component.Enums.SecurityType.Option;
                                        rIB.RightType = Options.IBClient.Component.Enums.RightType.Put;
                                        rIB.Expiry = DateTime.Parse(dr["Expiry Date"].ToString());
                                        rIB.StrikePrice = i;

                                        rIB.QueueId = QueueId;
                                        rIB.RequestId = helper.AddRequest(rIB).RequestId;

                                        //Add Option Call Data Requests
                                        rIB = new RequestIBClient();
                                        rIB.SecurityId = security.SecurityId;
                                        rIB.SecurityType = Options.IBClient.Component.Enums.SecurityType.Option;
                                        rIB.RightType = Options.IBClient.Component.Enums.RightType.Call;
                                        rIB.Expiry = DateTime.Parse(dr["Expiry Date"].ToString());
                                        rIB.StrikePrice = i;
                                        rIB.QueueId = QueueId;
                                        rIB.RequestId = helper.AddRequest(rIB).RequestId;
                                    }
                                }

                                if (dtWeeklyExpiry.Rows.Count > 0)
                                {
                                    if (security.IsWeekly)
                                    {

                                        //Add Option Put Weekly Data Requests
                                        rIB = new RequestIBClient();
                                        rIB.SecurityId = security.SecurityId;
                                        rIB.SecurityType = Options.IBClient.Component.Enums.SecurityType.Option;
                                        rIB.RightType = Options.IBClient.Component.Enums.RightType.Put;
                                        rIB.Expiry = DateTime.Parse(dtWeeklyExpiry.Rows[0].ItemArray[0].ToString());
                                        rIB.IsWeeklyOption = true;
                                        rIB.StrikePrice = i;
                                        rIB.QueueId = QueueId;
                                        rIB.RequestId = helper.AddRequest(rIB).RequestId;
                                    }
                                }
                            }
                        }
                        rowcount = rowcount + 1;
                        if ((rowcount % 10) == 0)
                            QueueId = QueueId + 1;
                    }
                }
                else
                {
                    this.SetTWSErrorMsg("No heartbeat between us and IB");
                    Log.LogMessage("No heartbeat between us and IB");
                    this.SetTWSErrorMsg("Re-establishing the heartbeat...");
                    Log.LogMessage("Re-establishing the heartbeat...");
                    connectClient();
                }
                //UpdateProgress(20);

                int maxIteration = 1;

                while (maxIteration <= 200)
                {
                    List<RequestIBClient> pendingRequests = new List<RequestIBClient>();
                    pendingRequests = helper.GetPendingRequest();
                    if (pendingRequests.Count > 0)
                    {
                        foreach (RequestIBClient req in pendingRequests)
                        {
                            Security sec = securities.Find(delegate(Security s) { return s.SecurityId == req.SecurityId; });

                            if (sec != null)
                            {
                                if (req.SecurityType == Component.Enums.SecurityType.Stock)
                                {
                                    contract = new Contract(sec.Symbol, "SMART", Krs.Ats.IBNet.SecurityType.Stock, "USD");
                                    if (client.Connected)
                                        client.RequestMarketData(req.RequestId, contract, null, true, false);
                                    else
                                    {
                                        this.SetTWSErrorMsg("No heartbeat between us and IB");
                                        Log.LogMessage("No heartbeat between us and IB");
                                        this.SetTWSErrorMsg("Re-establishing the heartbeat...");
                                        Log.LogMessage("Re-establishing the heartbeat...");
                                        connectClient();
                                        client.RequestMarketData(req.RequestId, contract, null, true, false);
                                    }
                                }

                                if (req.SecurityType == Component.Enums.SecurityType.Option)
                                {
                                    string expiry = String.Format("{0:yyyyMMdd}", req.Expiry);
                                    if (req.RightType == Component.Enums.RightType.Put)
                                        contract = new Contract(0, sec.Symbol.Trim(), Krs.Ats.IBNet.SecurityType.Option, expiry, (double)req.StrikePrice, Krs.Ats.IBNet.RightType.Put, "100", "SMART", "USD", string.Empty, string.Empty, SecurityIdType.None, string.Empty);
                                    if (req.RightType == Component.Enums.RightType.Call)
                                        contract = new Contract(0, sec.Symbol.Trim(), Krs.Ats.IBNet.SecurityType.Option, expiry, (double)req.StrikePrice, Krs.Ats.IBNet.RightType.Call, "100", "SMART", "USD", string.Empty, string.Empty, SecurityIdType.None, string.Empty);
                                    if (client.Connected)
                                        client.RequestMarketData(req.RequestId, contract, null, true, false);
                                    else
                                    {
                                        this.SetTWSErrorMsg("No heartbeat between us and IB");
                                        Log.LogMessage("No heartbeat between us and IB");
                                        this.SetTWSErrorMsg("Re-establishing the heartbeat...");
                                        Log.LogMessage("Re-establishing the heartbeat...");
                                        connectClient();
                                        client.RequestMarketData(req.RequestId, contract, null, true, false);
                                    }
                                }
                                helper.UpdateRequestIBClientSubmitted(req.RequestId);
                                maxIteration++;
                            }

                        }
                    }
                    else if (helper.GetCountPendingReqSubmitted() > 0)
                    {
                        Thread.Sleep(5000);
                    }
                    else
                        break;
                }
                DataSet ds = helper.GetTrackRequests();
                string submitted = ds.Tables["Table1"].Rows[0].ItemArray[0].ToString();
                string totalReq = ds.Tables["Table"].Rows[0].ItemArray[0].ToString();
                SetDeltaLabel("Requests " + submitted + " of " + totalReq + " submitted");
                Log.LogMessage("Requests " + submitted + " of " + totalReq + " submitted");
            }
            catch (Exception ex)
            {
                this.SetTWSErrorMsg("Error:" + ex.Message.ToString());
                Log.LogMessage(ex.Message.ToString());
            }
        }

        private void requestDeltabgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {

        }

        private void requestDeltabgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }


        private void refreshbgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {

                SqlHelper helper = new SqlHelper();
                DataTable dt = null;


                DisplayMarketData(helper.DisplayMarketData());
                //DisplayOptionData(helper.GetOptionTrigger());
                //DisplayOpenOrders(helper.GetOpenOrders());


                //Handle Request to update ConId
                dt = helper.GetPendingRequestsForConId();
                if (dt.Rows.Count > 0)
                {
                    if (client.Connected)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            string expiry = String.Format("{0:yyyyMMdd}", DateTime.Parse(dr["Expiry"].ToString()));

                            contract = new Contract(0, dr["Symbol"].ToString().Trim(), Krs.Ats.IBNet.SecurityType.Option, expiry, double.Parse(dr["Strike_Price"].ToString()), dr["Right_Type"].ToString().Trim() == Options.IBClient.Component.Enums.RightType.Put.ToString() ? Krs.Ats.IBNet.RightType.Put : Krs.Ats.IBNet.RightType.Call, string.Empty, "SMART", "USD", string.Empty, string.Empty, SecurityIdType.None, string.Empty);
                            client.RequestContractDetails(int.Parse(dr["id"].ToString().Trim()), contract);
                            helper.UpdateConIdSubmitted(int.Parse(dr["id"].ToString().Trim()));
                        }
                    }
                }

                Thread.Sleep(10000);

                //Handle Request to close ConId
                dt = helper.GetPendingRequestsForCloseConId();
                if (dt.Rows.Count > 0)
                {
                    if (client.Connected)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            string expiry = String.Format("{0:yyyyMMdd}", DateTime.Parse(dr["Expiry"].ToString()));

                            contract = new Contract(0, dr["Symbol"].ToString().Trim(), Krs.Ats.IBNet.SecurityType.Option, expiry, double.Parse(dr["Strike_Price"].ToString()), dr["Right_Type"].ToString().Trim() == Options.IBClient.Component.Enums.RightType.Put.ToString() ? Krs.Ats.IBNet.RightType.Put : Krs.Ats.IBNet.RightType.Call, string.Empty, "SMART", "USD", string.Empty, string.Empty, SecurityIdType.None, string.Empty);
                            client.RequestContractDetails(int.Parse(dr["id"].ToString().Trim()), contract);
                            helper.UpdateCloseConIdSubmitted(int.Parse(dr["id"].ToString().Trim()));
                        }
                    }
                }

                Thread.Sleep(10000);

                dt = helper.GetPlaceComboOrderRequest();

                if (dt.Rows.Count > 0)
                {
                    if (client.Connected)
                    {
                        client.RequestAllOpenOrders();
                        foreach (DataRow dr in dt.Rows)
                        {

                            ComboLeg sleg = new ComboLeg();
                            sleg.ConId = int.Parse(dr["BidConId"].ToString().Trim());
                            sleg.Ratio = 1;
                            sleg.Action = ActionSide.Sell;
                            sleg.Exchange = "SMART";

                            ComboLeg bleg = new ComboLeg();
                            bleg.ConId = int.Parse(dr["AskConId"].ToString().Trim()); ;
                            bleg.Ratio = 1;
                            bleg.Action = ActionSide.Buy;
                            bleg.Exchange = "SMART";
                            string expiry = String.Format("{0:yyyyMMdd}", DateTime.Parse(dr["Expiry"].ToString()));

                            contract = new Contract();

                            contract.Symbol = "USD";
                            contract.SecurityType = Krs.Ats.IBNet.SecurityType.Bag;
                            contract.Exchange = "SMART";
                            contract.Currency = "USD";

                            contract.ComboLegs.Add(sleg);
                            contract.ComboLegs.Add(bleg);

                            Krs.Ats.IBNet.Order order = new Krs.Ats.IBNet.Order();
                            order.Action = dr["Action"].ToString().Trim() == ActionSide.Sell.ToString() ? ActionSide.Sell : ActionSide.Buy;
                            order.OrderType = OrderType.Market;
                            order.TotalQuantity = int.Parse(dr["Size"].ToString());

                            client.PlaceOrder(int.Parse(dr["Id"].ToString()), contract, order);
                            this.SetTWSErrorMsg("Order Id " + dr["Id"].ToString() + " has been placed.");
                            client.RequestExecutions(34, new ExecutionFilter());
                            helper.UpdateComboOrderRequestSubmitted((int)dr["Id"]);

                        }
                    }
                }
                Thread.Sleep(2000);

            }
            catch (Exception ex)
            {
                this.SetTWSErrorMsg("Error:" + ex.Message.ToString());
                Log.LogMessage(ex.Message.ToString());
            }
        }


        private void refreshbgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //if (e.ProgressPercentage == 100)
            //    refresh.Close();
        }


        private void refreshbgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            gvMarketData.Enabled = true;
            //gvOpenOrders.Enabled = true;
            gvdeltaCompute.Enabled = true;
            //gvOptionTrigger.Enabled = true;
            refresh.Close();
        }
        #endregion

        private void GetExpiryDate(ListViewItem item)
        {
            if (this.lstViewExpiry.InvokeRequired)
            {
                var action = new Action<ListViewItem>(GetExpiryDate);
                Invoke(action, new[] { item });
                return;
            }
            // Do whatever you want with i
            item.Checked = false;
        }


    }
}


